package com.ping.redis;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author 浩子
 *整合shiro，将登陆用户缓存  
 *ssm整合shiro
 */
@Service
public class RedisSessionDao extends AbstractSessionDAO{
	
	public Logger logger =  LoggerFactory.getLogger(RedisSessionDao.class);
	
	@Autowired
	private RedisManager redisManager;
	@Autowired
	private RedisConfiguration conf;
	//session的密钥前缀
	private String keyPrefix = "shiro_redis_session:";
	
	
	private void saveSession(Session session){
		
		if(session == null || session.getId()==null){
			logger.error("session is null or sessionId is null");
			return;
		}
		
		byte[]key = getByteKey(session.getId());
        byte[]value = SerializeUtils.serialize(session);
        session.setTimeout(conf.getTimeout() * 1000);
        redisManager.set(key,value,conf.getExpire());
	}
	
	/**
	 * 将sesion转换成byte[] 类型
	 * @param sessionId
	 * @return
	 */
	private byte[] getByteKey(Serializable sessionId){
        String preKey = this.keyPrefix + sessionId;
        return preKey.getBytes();
    }

	/* 删除session的缓存
	 * @see org.apache.shiro.session.mgt.eis.SessionDAO#delete(org.apache.shiro.session.Session)
	 */
	@Override
	public void delete(Session session) {
		
		if(session == null || session.getId()==null){
			logger.error("session is null or sessionId is null");
			return;
		}
		
		redisManager.del(getByteKey(session.getId()));
	}

	/* 获取当前的所有session
	 * @see org.apache.shiro.session.mgt.eis.SessionDAO#getActiveSessions()
	 */
	@Override
	public Collection<Session> getActiveSessions() {
		
		Set<Session> sessions = new HashSet<Session>();
		Set<byte[]> keys= redisManager.keys(this.keyPrefix+"*");
		if(keys != null && keys.size()>0){
			for (byte[] key : keys) {
				Session session = (Session)SerializeUtils.deserialize(redisManager.get(key));
				sessions.add(session);
			}
		}
		return sessions;
	}

	/* 更新session的缓存
	 * @see org.apache.shiro.session.mgt.eis.SessionDAO#update(org.apache.shiro.session.Session)
	 */
	@Override
	public void update(Session session) throws UnknownSessionException {
		this.saveSession(session);
		
	}

	/* 创建这个session  并给予一个id
	 * @see org.apache.shiro.session.mgt.eis.AbstractSessionDAO#doCreate(org.apache.shiro.session.Session)
	 */
	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session,sessionId);  //将session 与sessionId  绑起来
        this.saveSession(session);
        return sessionId;
	}

	/* 用sessionId 索引到session
	 * @see org.apache.shiro.session.mgt.eis.AbstractSessionDAO#doReadSession(java.io.Serializable)
	 */
	@Override
	protected Session doReadSession(Serializable serializable) {
		 if(serializable == null)
	        {
	            logger.error("session id is null");
	            return  null;
	        }
	        Session session = (Session) SerializeUtils.deserialize(redisManager.get(getByteKey(serializable)));
	        return session;
	}

}
